package model

import (
	"autoclave/global"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"

var DB *gorm.DB

func init() {

	dbHost := global.AppConfig.Section("mysql").Key("host").String()
	dbPort := global.AppConfig.Section("mysql").Key("port").String()
	dbUser := global.AppConfig.Section("mysql").Key("user").String()
	dbPwd := global.AppConfig.Section("mysql").Key("passwd").String()
	dbName := global.AppConfig.Section("mysql").Key("database").String()
	charset := global.AppConfig.Section("mysql").Key("charset").String()
	//logMode, _ := global.AppConfig.Section("mysql").Key("logMode").Int()

	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=true&loc=Local", dbUser, dbPwd, dbHost, dbPort, dbName, charset)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second,   // Slow SQL threshold
			LogLevel:                  logger.Silent, // Log level; logger.Silent(关闭日志)Info(全部信息)
			IgnoreRecordNotFoundError: true,          // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,          // Don't include params in the SQL log
			Colorful:                  true,          // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		QueryFields:            true,
		Logger:                 newLogger,
		SkipDefaultTransaction: true, // 禁用事务, 默认开启
	})
	if err != nil {
		fmt.Println("gorm.Open error: ", err)
		return
	}

	sqlDB, err := db.DB()
	if err != nil {
		fmt.Println("DB.DB() error: ", err)
		return
	}
	//  设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)
	//  设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)
	//  设置了连接可复用的最大时间。10分钟不用的连接将放入连接池, 连接池满则关闭连接
	sqlDB.SetConnMaxLifetime(time.Minute * 10)
	DB = db
	fmt.Printf("%-32s%-32s\n", "mysql connect", "OK")

}
